<?php

namespace Xin\Setting\ThinkPHP;

use think\db\Query;
use think\Model;
use Xin\Setting\Exceptions\InvalidConfigureException;
use Xin\Setting\SettingManager;
use Xin\Support\Arr;
use Xin\Support\SQL;

/**
 * 配置模型
 *
 * @property int type
 * @property int sort
 * @property string value
 * @property string extra
 * @property int group
 */
class DatabaseSetting extends Model
{
	/**
	 * @var string
	 */
	protected $name = 'setting';

	/**
	 * 禁止写入创建时间
	 *
	 * @var bool
	 */
	protected $createTime = false;

	/**
	 * 禁止写入更新时间
	 *
	 * @var bool
	 */
	protected $updateTime = false;

	/**
	 * 插入数据自动完成
	 *
	 * @var array
	 */
	protected $insert = [
		'status' => 1,
	];

	/**
	 * @return object|SettingManager
	 */
	protected function manager()
	{
		return app('setting');
	}

	/**
	 * 获取数据分组
	 *
	 * @return mixed
	 * @throws InvalidConfigureException
	 */
	protected function getGroupTextAttr()
	{
		$groups = $this->manager()->getGroupList();
		$group = $this->getData('group');

		return isset($groups[$group]) ? $groups[$group] : "无";
	}

	/**
	 * 获取数据类型
	 *
	 * @return string
	 * @throws InvalidConfigureException
	 */
	protected function getTypeTextAttr()
	{
		$types = $this->manager()->getTypeList();
		$type = $this->getData('type');

		return isset($types[$type]) ? $types[$type] : "无";
	}

	/**
	 * 获取扩展配置信息
	 *
	 * @param $string
	 * @return array
	 */
	protected function getExtraAttr($string)
	{
		$type = $this->getOrigin('type');

		if ($type == 'object') {
			$result = json_decode($string, true);
			if ($result === null) {
				$result = [];
			}

			$values = $this->getAttr('value');
			foreach ($result as &$item) {
				$key = $item['name'];
				if (isset($values[$key])) {
					$item['value'] = $values[$key];
				} elseif (!isset($item['value'])) {
					$item['value'] = '';
				}
			}
			unset($item);

			return $result;
		}

		return Arr::parse($string);
	}

	/**
	 * 标题搜索器
	 * @param Query $query
	 * @param string $value
	 * @return void
	 */
	public function searchKeywordsAttr(Query $query, $value)
	{
		$values = SQL::keywords($value);
		if (empty($values)) {
			return;
		}

		$query->where(implode('|', ['name', 'title', 'alias']), 'like', $values);
	}
}
